# aegaeon_proto/watchdog.py
"""
Watchdog daemon: periodically check PROCESSING_LIST for stuck items (older than threshold)
and move them back to REQ_QUEUE to be retried.
"""

import os
import time
import json
import logging
import redis

REDIS_URL = os.environ.get("REDIS_URL", "redis://localhost:6379/0")
PROCESSING_LIST = "aegaeon:processing"
REQ_QUEUE = "aegaeon:requests"
CHECK_INTERVAL = int(os.environ.get("WATCHDOG_INTERVAL", "10"))
STALE_SECONDS = int(os.environ.get("WATCHDOG_STALE", "60"))

r = redis.Redis.from_url(REDIS_URL, decode_responses=True)
log = logging.getLogger("aegaeon.watchdog")
logging.basicConfig(level=logging.INFO)

def is_stale(item_str):
    try:
        obj = json.loads(item_str)
        created = float(obj.get("created", time.time()))
        return (time.time() - created) > STALE_SECONDS
    except Exception:
        # if cannot parse, treat as stale
        return True

def run_once():
    # get copy of processing list
    items = r.lrange(PROCESSING_LIST, 0, -1)
    if not items:
        return
    moved = 0
    for it in items:
        if is_stale(it):
            # push back to request queue and remove from processing list
            r.rpush(REQ_QUEUE, it)
            r.lrem(PROCESSING_LIST, 0, it)
            moved += 1
    if moved:
        log.info("Watchdog moved %d stale items back to requests queue", moved)

if __name__ == "__main__":
    log.info("Starting watchdog. CHECK_INTERVAL=%s STALE_SECONDS=%s", CHECK_INTERVAL, STALE_SECONDS)
    while True:
        try:
            run_once()
        except Exception:
            log.exception("watchdog loop error")
        time.sleep(CHECK_INTERVAL)
